package com.xn.app.muying.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.xn.app.muying.R;
import com.xn.app.muying.bean.Device;
import com.xn.app.muying.bean.TemperatureBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.AndroidBug54971Workaround;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.BluetoothEnvironment;
import com.xn.app.muying.util.BluetoothUtil;
import com.xn.app.muying.util.DateUtils;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.MyApplication;
import com.xn.app.muying.util.ToastUtil;
import com.xn.app.muying.util.VibratorUtil;
import com.xn.app.muying.view.CircularDiffusionView;
import com.zhuge.analysis.stat.ZhugeSDK;

import java.text.DecimalFormat;
import java.util.Date;


/**
 * 体温监测
 * Created by gaoge on 2017/2/4.
 */
public class TemperatureMonitoringActivity extends BaseActivity implements View.OnClickListener {
    //标题
    private Spinner title_name = null;
    //背景颜色
    private RelativeLayout relativelayout = null;
    //开始测量
    private TextView start_text = null;
    //蓝牙连接提示语
    private TextView bluetooth_textview = null;
    //设备信息布局
    private LinearLayout equipment_linearlayout = null;
    //查看曲线
    private TextView show_text = null;
    //设备号
    private TextView shebeihao_textview = null;
    //蓝牙图标
    private ImageView imageLanYa = null;
    //显示摄氏度
    private TextView text_sheshidu = null;
    //测量时间
    private TextView doing_time = null;
    //电池电量
    private ImageView battery = null;
    //设置按钮
    private ImageView img_set = null;
    //水波纹动画
    private CircularDiffusionView circularDiffusionView = null;
    //标题适配器
    private SpinnerAdpter spinnerAdpter = null;
    //记录当前是否正在监测
    private boolean lean = false;
    //默认每2秒更新一次体温数据
    private static final int DEFAULT_MONITOR = 2 * 1000;
    // 开始的时间
    private Date mStart = null;
    //测量的温度值
    private StringBuilder mValues;
    //判断提示框是否存在
    private boolean logShow = false;
    //数据库
    private DBManager db = null;
    //预设值的发烧温度
    private String number1 = "37.2";
    //预设值的蹬被子温度
    private String number2 = "25.1";
    //预设值的洗澡温度
    private String number3 = "20.1-40.1";
    //对于数据库字段名
    private int careType = 0;
    private String[] careString = {"FeverWarning", "SleepWarning", "ShowerWarning"};
    //当前模式的预警温度
    private String warningTemperature = "";
    //发烧提醒间隔时间/分钟
    private long feverNumber = 30;
    //蹬被子提醒间隔时间/分钟
    private long sleepNumber = 15;
    //洗澡提醒间隔时间/分钟
    private long bathNumber = 2;
    //定时提醒
    private long timer = 0;
    //记录已经测量的时间
    private String duration = null;
    //记录测量时间
    private StringBuilder mTime;
    //记录广播是否注册
    private boolean leanStart = false;
    //监测记录对象
    private TemperatureBean temperatureBean = null;
    //设备
    private Device d = null;
    //购买设备
    private TextView shop_textview=null;

    //设备连接成功，显示设备信息
    private static final int DEVICE_FOUND = 0x0001;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DEVICE_FOUND:
                    if(msg.obj!=null){
                        d = (Device) msg.obj;
                        setTemperatureData(d);
                    }

                    // 每隔DEFAULT_MONITOR时间，进行重新获取温度数据
//                    mHandler.postDelayed(mMonitor, DEFAULT_MONITOR);
                    break;
            }
        }
    };
    //定时获取数据
    private Runnable mMonitor = new Runnable() {
        @Override
        public void run() {
            BluetoothUtil.getInstance().startMonitorBroadcast(new BluetoothUtil.OnDeviceFound() {
                @Override
                public void onLeScan(Device blueInfo) {
                    Message msg = mHandler.obtainMessage();
                    msg.what = DEVICE_FOUND;
                    msg.obj = blueInfo;
                    msg.sendToTarget();
                }
            });
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AndroidBug54971Workaround.assistActivity(findViewById(android.R.id.content));
        //加载布局
        setContentView(R.layout.temperature_activity);
        //如果手机系统大于等于5.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
//            window.setNavigationBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //如果手机系统大于等于4.4并且小于等于5.0
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "体温监测");
        } catch (Exception e) {
            e.printStackTrace();
        }
        //统一管理activity
        MyApplication.getInstance().addActivity(this);
        //初始化组件
        initialization();
    }

    //初始化
    private void initialization() {
        db = new DBManager(this);
        //返回键
        findViewById(R.id.img_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (lean) {
                    startActivity(new Intent(TemperatureMonitoringActivity.this, MainActivity.class));
                } else {
                    if (leanStart) {
                        // 停止扫描
//                        BluetoothUtil.getInstance().stopMonitorBroadcast();
                        //关闭
                        BluetoothUtil.getInstance().unregisterReceiver();
                    }
                    finish();
                }
                overridePendingTransition(R.anim.back_lift_exit, R.anim.back_right_enter);
            }
        });
        circularDiffusionView = (CircularDiffusionView) findViewById(R.id.cdv);
        imageLanYa = (ImageView) findViewById(R.id.imageview);
        imageLanYa.setImageResource(R.mipmap.tiwen_lanya2);
        text_sheshidu = (TextView) findViewById(R.id.text_sheshidu);
        doing_time = (TextView) findViewById(R.id.doing_time);
        relativelayout = (RelativeLayout) findViewById(R.id.relativelayout);
        title_name = (Spinner) findViewById(R.id.title_name);
        img_set = (ImageView) findViewById(R.id.img_set);
        battery = (ImageView) findViewById(R.id.battery);
        shebeihao_textview = (TextView) findViewById(R.id.shebeihao_textview);
        bluetooth_textview = (TextView) findViewById(R.id.bluetooth_textview);
        equipment_linearlayout = (LinearLayout) findViewById(R.id.equipment_linearlayout);
        start_text = (TextView) findViewById(R.id.start_text);
        show_text = (TextView) findViewById(R.id.show_text);
        shop_textview= (TextView) findViewById(R.id.shop_textview);
        start_text.setOnClickListener(this);
        show_text.setOnClickListener(this);
        img_set.setOnClickListener(this);
        shop_textview.setOnClickListener(this);
        //设置标题
        initMySpinner();
        try {
            if (db.selectNull(DBManager.TEMPERATRUE_SET_TABLE) != 0) {
            } else {
                //设置体温监测基础设置
                db.insertTemperatureSet(number1, number2, number3);
                //0代表铃声   1代表震动  2代表铃声+震动 3代表无
                db.updateTemperatureSetSingle("RemindWay", 0);
            }
        } catch (Exception e) {
            finish();
        }
    }

    /**
     * 检测设备是否支持蓝牙4.0，如果不支持就自动退出程序,如果支持就初始化蓝牙相关操作
     */
    private void checkBluetoothEnvironment() {
        if (!BluetoothEnvironment.isDeviceSupported(this)) {
            ToastUtil.showToast(this, "本手机不支持蓝牙4.0,暂时无法使用本功能");
        } else {
            BluetoothUtil.getInstance().initBluetooth(this, null);
        }
    }

    /**
     * 检测蓝牙是否打开
     */
    private boolean checkBluetoothOpen() {
        if (!BluetoothUtil.getInstance().isBluetoothOpen()) {
//           // 如果本地蓝牙没有开启，则开启
            if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
                Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(mIntent, 1);
            }
            return false;
        } else {
            return true;
        }
    }

    /**
     * 接受返回的信息
     *
     * @param requestCode
     * @param resultCode
     * @param data        返回来的数据
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            //蓝牙打开成功
            case 1:
                if (resultCode == Activity.RESULT_OK) {
                    //开始监测
                    openOrClose(0);
                }
                break;
        }
    }

    /**
     * 开始搜索蓝牙设备
     */
    private void startMinitor() {
        mHandler.post(mMonitor);
    }

    /**
     * 停止测量
     */
    private void mOnStop() {
        leanStart = false;
        // 停止扫描
//        BluetoothUtil.getInstance().stopMonitorBroadcast();
        //关闭
        BluetoothUtil.getInstance().unregisterReceiver();
        lean = false;
        // 设置界面
        circularDiffusionView.stop();
        start_text.setBackgroundResource(R.drawable.button_fen_white);
        start_text.setTextColor(TemperatureMonitoringActivity.this.getResources().getColor(R.color.white));
        start_text.setText("开始测量");
        bluetooth_textview.setVisibility(TextView.VISIBLE);
        shop_textview.setVisibility(TextView.VISIBLE);
        equipment_linearlayout.setVisibility(LinearLayout.GONE);
        show_text.setVisibility(TextView.GONE);
        relativelayout.setBackgroundResource(R.mipmap.tiwen_fen);
        imageLanYa.setImageResource(R.mipmap.tiwen_lanya2);
        text_sheshidu.setVisibility(TextView.GONE);
        // 移除线程
        mHandler.removeCallbacks(mMonitor);
        // 重置开始时间和体温值
        mStart = null;
        mValues = null;
        //关闭蓝牙
        if (BluetoothUtil.getInstance().isBluetoothOpen()) {
            BluetoothUtil.getInstance().closeBluetooth();
        }
    }


    /**
     * 显示体温信息等操作
     */
    private int mPastMinute = 0;

    private void setTemperatureData(Device d) {
        // 第一次要初始化开始时间
        if (mStart == null) {
            temperatureBean = new TemperatureBean();
            lean = true;
            mPastMinute = 0;
            mStart = new Date();
            mValues = new StringBuilder();
            mTime = new StringBuilder();
            //设置动画属性
            bluetooth_textview.setVisibility(TextView.GONE);
            shop_textview.setVisibility(TextView.GONE);
            equipment_linearlayout.setVisibility(LinearLayout.VISIBLE);
            circularDiffusionView.setNumber(5);
            circularDiffusionView.setTransparency(100);
            circularDiffusionView.setMaxWidth(100);
            circularDiffusionView.setDiffuseWidth(6);
            circularDiffusionView.setAmplitude(2);
            circularDiffusionView.setSpeedThread(100);
            circularDiffusionView.stop();
            circularDiffusionView.start(imageLanYa);
            imageLanYa.setImageResource(R.mipmap.tiwen_zhengchang);
            start_text.setText("结束测量");
            start_text.setClickable(true);
            text_sheshidu.setVisibility(TextView.VISIBLE);
            start_text.setBackgroundResource(R.drawable.button_white_fen);
            start_text.setTextColor(TemperatureMonitoringActivity.this.getResources().getColor(R.color.sys_fen));
            show_text.setVisibility(TextView.VISIBLE);
            //设置设备号
            shebeihao_textview.setText(d.getDeviceId());
            //向监测对象中填写数据
            //设置监测分类
            temperatureBean.setType(careType);
            //设置监测状态
            temperatureBean.setState(0);
            //写入开始监测时间
            temperatureBean.setStartTime(DateUtils.gettimeDate());
        }
        //获取当前预警温度
        warningTemperature = db.selectTemperature(careString[careType]);
        // 设置体温值
        String value = formatValue(d.getTemperature());
        text_sheshidu.setText(value + "℃");
        // 判断提示是否需要报警
        showFeverDialog(Float.parseFloat(value), warningTemperature);


        //当测量时间超过1分钟就统计一次体温值
        //对于不需要实时变更的数据，每分钟更新一次，提升优化
        Date date = new Date();
        if (DateUtils.calculateDurationMinutes(mStart, date) - mPastMinute >= 0) {
            mValues.append(value + ";");
            mTime.append(DateUtils.getDateToStringTimeHm(date.getTime()) + ";");
            mPastMinute++;
            // 设置测量时间
            duration = DateUtils.calculateDuration(mStart, date);
            doing_time.setText(duration);
            // 设置设备电量
            if (d.getBatteryPower() >= 80) {
                battery.setImageResource(R.mipmap.battery5);
            } else if (d.getBatteryPower() < 80 && 60 <= d.getBatteryPower()) {
                battery.setImageResource(R.mipmap.battery4);
            } else if (d.getBatteryPower() < 60 && d.getBatteryPower() >= 40) {
                battery.setImageResource(R.mipmap.battery3);
            } else if (d.getBatteryPower() < 40 && d.getBatteryPower() >= 20) {
                battery.setImageResource(R.mipmap.battery2);
            } else if (d.getBatteryPower() < 20 && d.getBatteryPower() >= 10) {
                battery.setImageResource(R.mipmap.battery1);
            } else if (d.getBatteryPower() < 10) {
                battery.setImageResource(R.mipmap.battery0);
            }
            //向监测对象中填写数据
            //写入体温数据
            temperatureBean.setData(mValues.toString());
            //写入体温数据对应时间
            temperatureBean.setData_time(mTime.toString());
            //写入监测时间
            temperatureBean.setTotalTime(duration);
        }
    }

    /**
     * 格式化体温数据
     *
     * @param temperature
     * @return
     */
    private String formatValue(float temperature) {
        return new DecimalFormat("##.#").format(temperature);
    }

    /**
     * 设置报警监听
     *
     * @param value
     */
    private void showFeverDialog(float value, String data) {
        if (!logShow) {
            if (careType == 2) {
                if (value > Float.parseFloat(data.split("-")[1])) {
                    //高温提示
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_juse);
                    imageLanYa.setImageResource(R.mipmap.tiwen_gao);
                    //预警提示
                    showLog("请注意，水温当前为" + value + "℃", bathNumber);
                } else if (value < Float.parseFloat(data.split("-")[0])) {
                    //高温提示
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_juse);
                    imageLanYa.setImageResource(R.mipmap.tiwen_gao);
                    //预警提示
                    showLog("请注意，水温当前为" + value + "℃", bathNumber);
                } else {
                    //温度正常
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_fen);
                    imageLanYa.setImageResource(R.mipmap.tiwen_zhengchang);
                }
            } else if (careType == 0) {
                if (value > Float.parseFloat(data)) {
                    //高温提示
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_juse);
                    imageLanYa.setImageResource(R.mipmap.tiwen_gao);
                    //预警提示
                    showLog("请注意，体温当前为" + value + "℃", feverNumber);

                } else {
                    //温度正常
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_fen);
                    imageLanYa.setImageResource(R.mipmap.tiwen_zhengchang);
                }
            } else if (careType == 1) {
                if (value < Float.parseFloat(data)) {
                    //高温提示
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_juse);
                    imageLanYa.setImageResource(R.mipmap.tiwen_gao);
                    //预警提示
                    showLog("请注意，当前温度为" + value + "℃", sleepNumber);
                } else {
                    //温度正常
                    relativelayout.setBackgroundResource(R.mipmap.tiwen_fen);
                    imageLanYa.setImageResource(R.mipmap.tiwen_zhengchang);
                }
            }
        }

    }

    /**
     * 设置标题
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void initMySpinner() {
        String[] phones = {"发烧看护", "蹬被看护", "洗澡看护"};
        spinnerAdpter = new SpinnerAdpter(phones, this);
        title_name.setAdapter(spinnerAdpter);
        title_name.setPopupBackgroundResource(R.drawable.button_transparency);

        //设置选择事件
        title_name.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                careType = i;
                //清空定时
                timer = 0;
                //切换状态提示
                if (lean) {
                    setSeaveLog(1);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    /**
     * 单击事件
     *
     * @param view
     */

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //开始监测
            case R.id.start_text:
                if (start_text.getText().toString().equals("结束测量")) {
                    //保存日志
                    setSeaveLog(0);
                } else {
                    //开始监测
                    openOrClose(0);
                }
                break;
            //设置
            case R.id.img_set:
                startActivity(new Intent(TemperatureMonitoringActivity.this, TemperatureSetActivity.class));
                break;
            //查看曲线
            case R.id.show_text:
                Intent intent = new Intent(TemperatureMonitoringActivity.this, TemperatureSeeCurveActivity.class);
                intent.putExtra("type", 0);
                intent.putExtra("time", DateUtils.getTimeMD());
                intent.putExtra("careType", careType);
                intent.putExtra("state", lean);
                intent.putExtra("startTime", DateUtils.getDateToStringYMDHM(mStart.getTime()));
                intent.putExtra("continuousTime", duration);
                intent.putExtra("temperatureData", mValues.toString());
                intent.putExtra("timeData", mTime.toString());
                startActivity(intent);
                break;
            //营养中心
            case R.id.shop_textview:
                Intent intent1 = new Intent(TemperatureMonitoringActivity.this, WebActivity.class);
                intent1.putExtra("title", "营养中心");
                intent1.putExtra("url", APIMethod.WeiDianTiWen);
                startActivity(intent1);
                break;
        }
    }

    //加载框
    MyAlertDialog dialog1 = null;

    /**
     * 保存日记提示弹出框
     *
     * @param i 0代表用户点击停止监测   1代表切换看护状态
     */
    private void setSeaveLog(final int i) {
        try {
            logShow = true;
            //加载弹出框
            dialog1 = new MyAlertDialog();
            dialog1.Temperature_Dialog(TemperatureMonitoringActivity.this, R.layout.save_log_dialog);
            TextView data = dialog1.getData();
            TextView getConfirm_text = dialog1.getConfirm_text();
            TextView getCancel_text = dialog1.getCancel_text();
            //设置内容
            if (i == 1) {
                data.setText("切换看护状态，是否保存看护日记？");
            } else {
                data.setText("是否保存看护日记？");
            }
            //设置取消按钮
            getCancel_text.setText("否");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog1.dismiss();
                    logShow = false;
                    if (i == 0) {
                        //关闭监测
                        openOrClose(1);
                    } else {
                        //重置数据
                        temperatureBean = new TemperatureBean();
                        mPastMinute = 0;
                        mStart = new Date();
                        mValues = new StringBuilder();
                        mTime = new StringBuilder();
                        //设置监测分类
                        temperatureBean.setType(careType);
                        //设置监测状态
                        temperatureBean.setState(0);
                        //写入开始监测时间
                        temperatureBean.setStartTime(DateUtils.gettimeDate());
                    }

                }
            });
            //设置确认按钮
            getConfirm_text.setText("是");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog1.dismiss();
                    logShow = false;
                    //向监测对象中填写数据
                    //写入结束时间
                    temperatureBean.setEndTime(DateUtils.gettimeDate());
                    //更新状态
                    temperatureBean.setState(1);
                    //将数据添加到数据库
                    db.insertTemperatureData(temperatureBean.getType(), temperatureBean.getState(), temperatureBean.getStartTime()
                            , temperatureBean.getEndTime(), temperatureBean.getTotalTime(), temperatureBean.getData(), temperatureBean.getData_time(), temperatureBean.getWarningRecord()
                            , temperatureBean.getNote(), temperatureBean.getMethod(), temperatureBean.getImgRecord());
                    if (i == 0) {
                        //关闭监测
                        openOrClose(1);
                    } else {
                        //重置数据
                        temperatureBean = new TemperatureBean();
                        mPastMinute = 0;
                        mStart = new Date();
                        mValues = new StringBuilder();
                        mTime = new StringBuilder();
                        //设置监测分类
                        temperatureBean.setType(careType);
                        //设置监测状态
                        temperatureBean.setState(0);
                        //写入开始监测时间
                        temperatureBean.setStartTime(DateUtils.gettimeDate());
                    }

                }
            });
        } catch (Exception e) {
        }
    }

    //加载框
    MyAlertDialog dialog2 = null;

    private void showLog(String cintent, long time) {
        if (timer < DateUtils.getNumberDate() - time * 60 * 1000) {
            //记录弹出框当前状态
            logShow = true;
            final int type = Integer.parseInt(db.selectTemperature("RemindWay")); //3 不处理
            if (type == 0) {
                //手机铃声
                new VibratorUtil().startAlarm(getApplicationContext());
            } else if (type == 1) {
                //手机震动
                VibratorUtil.Vibrate(getApplicationContext(), true);
            } else if (type == 2) {
                //铃声+震动
                new VibratorUtil().startAlarm(getApplicationContext());
                VibratorUtil.Vibrate(getApplicationContext(), true);
            }
            //加载弹出框
            dialog2 = new MyAlertDialog();
            dialog2.Temperature_Dialog(TemperatureMonitoringActivity.this, R.layout.save_log_dialog);
            TextView data = dialog2.getData();
            TextView getConfirm_text = dialog2.getConfirm_text();
            TextView getCancel_text = dialog2.getCancel_text();
            /**温度预警，提示用户是否修改温度*/
            //设置内容
            data.setText(cintent);
            //设置取消按钮
            getCancel_text.setText("设置报警温度");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    timer = DateUtils.getNumberDate();
                    logShow = false;
                    dialog2.dismiss();
                    if (type == 0) {
                        VibratorUtil.closeMediaPlayer();
                    } else if (type == 1) {
                        VibratorUtil.closeVib();
                    } else if (type == 2) {
                        VibratorUtil.closeMediaPlayer();
                        VibratorUtil.closeVib();
                    }
                    startActivity(new Intent(TemperatureMonitoringActivity.this, TemperatureSettingActivity.class).putExtra("type", 0));
                }
            });
            //设置确认按钮
            getConfirm_text.setText("知道了");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    timer = DateUtils.getNumberDate();
                    logShow = false;
                    dialog2.dismiss();
                    if (type == 0) {
                        VibratorUtil.closeMediaPlayer();
                    } else if (type == 1) {
                        VibratorUtil.closeVib();
                    } else if (type == 2) {
                        VibratorUtil.closeMediaPlayer();
                        VibratorUtil.closeVib();
                    }
                }
            });
        }
        if (timer == 0) {
            timer = DateUtils.getNumberDate();
        }
    }

    /**
     * 开启或者关闭监测
     *
     * @param i 0代表开启   1代表关闭
     */
    String[] str = {Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION};

    private void openOrClose(int i) {
        // 检测设备是否支持蓝牙4.0
        checkBluetoothEnvironment();
        if (i == 0) {
            //动态注册权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        str,
                        1);
            } else {
                // 检测蓝牙是否打开
                if (checkBluetoothOpen()) {
                    start_text.setText("正在连接设备...");
                    start_text.setClickable(false);
                    circularDiffusionView.setNumber(10);
                    circularDiffusionView.setTransparency(150);
                    circularDiffusionView.setMaxWidth(200);
                    circularDiffusionView.setDiffuseWidth(6);
                    circularDiffusionView.setAmplitude(1);
                    circularDiffusionView.setSpeedThread(30);
                    circularDiffusionView.start(imageLanYa);
                    leanStart = true;
                    startMinitor();
                }
            }
        } else if (i == 1) {
            mOnStop();
        }
    }

    /**
     * 标题适配器
     */
    public class SpinnerAdpter extends BaseAdapter {
        private String[] list;
        private Context context;// 上下文
        private LayoutInflater layoutInflater;

        public SpinnerAdpter(String[] list, Context context) {
            super();
            this.list = list;
            this.context = context;
            layoutInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        // getView什么时候执行
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder viewHolder = null;
            if (convertView == null) {
                convertView = layoutInflater.inflate(R.layout.spinner_item, null); // 创建list_item.xml布局文件的视图
                viewHolder = new ViewHolder();
                viewHolder.name = (TextView) convertView.findViewById(R.id.name);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.name.setText(list[position]);
            return convertView;
        }

    }

    class ViewHolder {
        private TextView name = null;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (lean) {
                startActivity(new Intent(TemperatureMonitoringActivity.this, MainActivity.class));
            } else {
                if (leanStart) {
                    // 停止扫描
//                    BluetoothUtil.getInstance().stopMonitorBroadcast();
                    //关闭
                    BluetoothUtil.getInstance().unregisterReceiver();
                }
                finish();
            }
            overridePendingTransition(R.anim.back_lift_exit, R.anim.back_right_enter);
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
